﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SQLServerHealthCheck.Model;
using AG.Utilities;

namespace SQLServerHealthCheck.SQLServer.IssueTypes
{
    public class DatabaseCheckSlowBackup : IssueTypeCheckBase
    {
        public DatabaseCheckSlowBackup()
        {
            IssueTypeId = 3015;
        }

        public override void Check()
        {
            try
            {
                HealthCheckDataContext dc = new HealthCheckDataContext(System.Configuration.ConfigurationManager.AppSettings["ConnectionStringSSHCDatabase"]);
                Issue issue;

                var ServerQry = from d in dc.Databases
                                where d.SourceDatabaseId == null
                                select d;
                //Get Issuetype object  And Create a new  Global issue object 

                IssueType issueType = dc.IssueTypes.FirstOrDefault(i => i.IssueTypeId == IssueTypeId);

                
                ThresholdValue thresholdValue= dc.ThresholdValues.FirstOrDefault(t => t.IssueTypeID == IssueTypeId && t.ThresholdValueID == 1);

                int minBakupSpeed = (int)thresholdValue.Value;
                foreach (var item in ServerQry)
                {
                    //Get Issuetype object
                    if (item.LatestFullBackup != null)
                    {
                        DateTime end = Convert.ToDateTime(item.LatestFullBackup);
                        DateTime start = Convert.ToDateTime(item.LatestFullBackupStart);
                        TimeSpan diff = end - start;
                        double speed = Convert.ToDouble(item.LatestFullBackupSize / diff.TotalMinutes);


                        if (speed < thresholdValue.Value)
                        {

                            issue = new Issue();

                            issue.IssueType = issueType;
                            issue.TargetId = item.DatabaseID;
                            issue.Description = issueType.Description.Replace("{Database}", item.DatabaseName);

                            dc.Issues.InsertOnSubmit(issue);
                            dc.SubmitChanges();
                        }
                    }
                }

               

            }
            catch (Exception ex)
            {
                Logger.Error(ex);
            }
        }


    }








}
